<template>
    <div class="pop-mappoint-selection">
        <template v-if="company_cp.map_tencent_KEY">
            <div class="content-box">
                <div id="tencentMap" class="bm-view"></div>
            </div>
            <div><span>经度：</span>{{ roughly_lnglat.lng }} <span class="ml20">纬度：</span>{{ roughly_lnglat.lat }}</div>
        </template>
        <template v-else>
            <div class="third-party-link-container">
                <div class="warning-info">
                    <i class="el-icon-warning warning-icon"></i>
                    <span class="warning-text">根据地址，需要在第三方平台获取经纬度坐标</span>
                </div>
                <div class="address-link-section">
                    <div class="address-display">
                        <i class="el-icon-location-outline location-icon"></i>
                        <span class="address-text">{{ addr }}</span>
                    </div>
                    <div class="external-link" @click="handleGetCoordinates">
                        <span class="link-text">复制地址，并去获取坐标</span>
                        <i class="el-icon-top-right external-icon"></i>
                    </div>
                </div>
                <div class="address-link-section mt10">
                    <div class="address-display">
                        <span class="address-text">粘贴坐标：</span>
                    </div>
                    <el-input v-model="crip_lnglat" @blur="handleCripBlur" placeholder="坐标格式案例：23.232161,113.289872"
                        style="width: calc(100% - 95px)"></el-input>
                </div>
            </div>
        </template>
    </div>
</template>

<script>
import localStore from "@/js/LocalStore.js";
export default {
    props: {
        addr: {
            type: String,
            default: ''
        },
        latlon: {
            type: Object,
            default: () => ({})
        }
    },
    watch: {
        addr: {
            handler(newVal) {
                if (newVal) {
                    let cp = localStore.getCpInfo();
                    this.company_cp = cp
                    if (cp?.map_tencent_KEY) {
                        this.updateMapLocation(newVal);
                    }
                }
            },
            deep: true,
        },
        latlon: {
            handler(newVal) {
                if (newVal && newVal.latitude && newVal.longitude) {
                    this.crip_lnglat = newVal.latitude + ',' + newVal.longitude
                    this.roughly_lnglat = {
                        lng: newVal.longitude,
                        lat: newVal.latitude
                    }
                }
            },
            deep: true,
        }
    },
    data() {
        return {
            dialogVisible: false,
            search_input: "", //搜索内容
            roughly_address: "", //地图地址
            roughly_lnglat: { lng: 0, lat: 0 }, //地图经纬度
            detailed_address: "", //详细地址
            center: { lng: 0, lat: 0 },
            zoom: 16,
            map: null,
            geocoder: null,
            currentMarker: null,
            company_cp: {},
            crip_lnglat: '',
        };
    },
    mounted() {
        let cp = localStore.getCpInfo();
        this.company_cp = cp
        if (this.company_cp?.map_tencent_KEY) {
            this.loadMap();
        }
    },
    methods: {

        handleCripBlur() {
            if (!this.crip_lnglat || this.crip_lnglat.trim() === '') {
                this.$message.error('经纬度输入为空')
                return
            }
            let ll = this.crip_lnglat.split(',')
            // 验证格式：应该有两个数值（纬度,经度）
            if (ll.length !== 2) {
                this.$message.error('经纬度格式错误，请输入格式：纬度,经度')
                return
            }
            // 去除空格并转换为数字
            const lat = parseFloat(ll[0].trim()) // 纬度
            const lng = parseFloat(ll[1].trim()) // 经度
            if (isNaN(lat) || isNaN(lng)) {
                this.$message.error('经纬度必须为有效数字')
                return
            }
            // 验证经纬度范围：纬度 -90 到 90，经度 -180 到 180
            if (lat < -90 || lat > 90) {
                this.$message.error('纬度范围应在-90到90之间')
                return
            }
            if (lng < -180 || lng > 180) {
                console.log('经度超出有效范围(-180到180)')
                this.$message.error('经度范围应在-180到180之间')
                return
            }
            this.roughly_lnglat = {
                lng: lng.toFixed(8),
                lat: lat.toFixed(8)
            }
            // 发出事件通知父组件
            this.$emit('mapLnglat', this.roughly_lnglat)
        },

        async loadMap() {
            // I7EBZ-IJILI-DETG5-5WZ27-5NRRV-M3BNM
            console.log("this.company_cp?.map_tencent_KEY==", this.company_cp?.map_tencent_KEY)
            await this.loadScript(`https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=${this.company_cp?.map_tencent_KEY}`); // I7EBZ-IJILI-DETG5-5WZ27-5NRRV-M3BNM
            if (typeof TMap === 'undefined') {
                console.error('TMap 未正确加载');
                return;
            }
            const center = new TMap.LatLng(36.87184493866717, 104.81227397918703);
            this.map = new TMap.Map(document.getElementById('tencentMap'), {
                center: center,
                zoom: this.zoom,
                pitch: 0,
                rotation: 0,
                viewMode: '2D',
                mapStyleId: 'style1',
                baseMap: {
                    type: 'vector',
                    features: ['base', 'point', 'road'],
                    showControl: false
                },
                scaleControl: false,
                zoomControl: false,
                compassControl: false,
                mapTypeControl: false,
                draggable: true,
                scrollwheel: false,
                disableDoubleClickZoom: true
            });
            // 隐藏控件
            const style = document.createElement('style');
            style.innerHTML = `
                .tmap-scale-control, .tmap-zoom-control, .tmap-compass-control {
                    display: none !important;
                }
            `;
            document.head.appendChild(style);
            // 初始化地理编码服务
            this.geocoder = new TMap.service.Geocoder();
            // 如果初始有地址，直接解析
            if (this.addr) {
                this.updateMapLocation(this.addr);
            }
        },
        async updateMapLocation(address) {
            if (!address) return;
            if (!this.map || !this.geocoder) return;
            try {
                const result = await this.geocoder.getLocation({ address });
                if (result && result.result && result.result.location) {
                    const location = result.result.location;
                    const newCenter = new TMap.LatLng(location.lat, location.lng);
                    this.map.setCenter(newCenter);
                    // 清除旧标记
                    if (this.currentMarker) {
                        this.currentMarker.setMap(null);
                    }
                    // 创建标记（用图片icon，不用MarkerStyle）
                    this.currentMarker = new TMap.MultiMarker({
                        map: this.map,
                        geometries: [{
                            id: 'marker',
                            position: newCenter,
                            icon: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker.png',
                            width: 12,
                            height: 12,
                            anchor: { x: 6, y: 12 }
                        }]
                    });
                    // this.roughly_address = `经度: ${location.lng.toFixed(6)}, 纬度: ${location.lat.toFixed(6)}`;
                    this.roughly_lnglat = { lng: location.lng.toFixed(8), lat: location.lat.toFixed(8) };
                    this.$emit('mapLnglat', this.roughly_lnglat);
                } else {
                    console.error('地址解析失败', result);
                }
            } catch (error) {
                console.error('地址解析请求失败:', error);
            }
        },
        loadScript(url) {
            return new Promise((resolve) => {
                // 防止重复加载
                if (document.querySelector(`script[src='${url}']`)) {
                    resolve();
                    return;
                }
                const script = document.createElement('script');
                script.src = url;
                script.onload = resolve;
                document.head.appendChild(script);
            });
        },
        popAddress() {
            let text = this.roughly_address + this.detailed_address;
            this.dialogVisible = false;
            this.$emit('mapText', text);
        },
        searchFun() {
            // 可选：实现搜索功能
        },
        handleGetCoordinates() {
            uni.setClipboardData({
                data: this.addr,
                success: function () {
                    setTimeout(() => {
                        const mapUrl = `https://lbs.qq.com/getPoint/`
                        window.open(mapUrl, '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes')
                    }, 1500);
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.bm-view {
    width: 100%;
    height: 200px;
}

// 第三方链接容器样式
.third-party-link-container {
    padding: 20px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: 1px solid #dee2e6;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }
}

// 警告信息样式
.warning-info {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 12px 16px;
    background: rgba(255, 193, 7, 0.1);
    border: 1px solid rgba(255, 193, 7, 0.3);
    border-radius: 8px;

    .warning-icon {
        color: #f39c12;
        font-size: 18px;
        margin-right: 8px;
        animation: pulse 2s infinite;
    }

    .warning-text {
        color: #856404;
        font-size: 14px;
        font-weight: 500;
    }
}

// 地址链接区域
.address-link-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: white;
    border-radius: 10px;
    border: 1px solid #e9ecef;
    transition: all 0.3s ease;

    &:hover {
        border-color: #4096ff;
        background: #f8f9ff;
    }
}

// 地址显示区域
.address-display {
    display: flex;
    align-items: center;
    flex: 1;

    .location-icon {
        color: #6c757d;
        font-size: 16px;
        margin-right: 8px;
    }

    .address-text {
        color: #495057;
        font-size: 14px;
        line-height: 1.5;
        word-break: break-all;
    }
}

// 外部链接样式
.external-link {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    background: linear-gradient(135deg, #4096ff 0%, #1677ff 100%);
    color: white;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(64, 150, 255, 0.3);
    margin-left: 16px;
    min-width: 120px;
    justify-content: center;

    &:hover {
        background: linear-gradient(135deg, #1677ff 0%, #0958d9 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 16px rgba(64, 150, 255, 0.4);
    }

    &:active {
        transform: translateY(0);
    }

    .link-text {
        font-size: 14px;
        font-weight: 500;
        margin-right: 6px;
    }

    .external-icon {
        font-size: 14px;
        transition: transform 0.3s ease;
    }

    &:hover .external-icon {
        transform: translate(2px, -2px);
    }
}

// 警告图标动画
@keyframes pulse {
    0% {
        transform: scale(1);
    }

    50% {
        transform: scale(1.1);
    }

    100% {
        transform: scale(1);
    }
}

.pop-mappoint-selection {
    .dialog-footer {
        text-align: center;
    }

    .content-box {
        height: 200px;
        width: 400px;
        border: 1px solid #dcdfe6;
        position: relative;

        ::v-deep.search-box {
            width: 400px;
            position: absolute;
            left: calc(50% - 200px);
            top: 50px;

            .input-w {
                width: 330px;
            }

            .el-input__inner {
                border-right: none;
                border-radius: 4px 0 0 4px;
            }

            .el-button {
                border-radius: 0 4px 4px 0;
            }
        }
    }

    .info-box {
        margin-top: 10px;

        .input-wd {
            width: 200px;
            margin-right: 10px;
        }

        .input-w {
            width: calc(100% - 210px);
        }
    }
}
</style>
